import myAxios from 'axios'
import qs from 'qs'
import oBaseConfig from '@/config/env'
import moment from 'moment'
import {getToken, setToken} from '@/middleware/validateInfo'

// var instance = myAxios.create({
//   baseURL: oBaseConfig.oBaseRoute.baseURL,
//   timeout: 10000,
//   withCredentials: true
// })
// instance.defaults.headers.common['Authorization'] = ''
export const Http = (url = '', data = {}, oParams = {}) => {
  let method = oParams.method || 'POST'
  method = method.toUpperCase()
  let route = oParams.route || 'wxapi'
  let baseRoute = oBaseConfig.oBaseRoute[route]
  // if (process.env.ENV_CONFIG !== 'dev') {
  if (!url.startsWith('http')) {
    url = baseRoute + url
  }
  // }
  if (!data.ts) {
    data.ts = moment().format('YYYYMMDDHHmmss')
  }
  let params =
    {
      method: method,
      url: url,
      headers: {
        // 'Content-Type': 'application/json;charset=utf-8'
        'Content-Type': 'application/x-www-form-urlencoded'
        // 'Access-Control-Allow-Credentials': true
      },
      // baseURL: '/shebao'
      baseURL: '/shebao/api/v1',
      transformRequest: [function (data) {
        data = qs.stringify(data)
        return data
      }]
    }
  params.headers.token = getToken()
  if (method === 'GET') {
    params.params = data
  } else {
    params.data = data
  }
  return myAxios(params).then(result => {
    let resultData = result.data
    if (resultData.result === 999) {
      setToken()
      return {}
    }
    return resultData
  }).then(reqResult => {
    return reqResult
  }).catch(error => {
    console.log('request error-----------', error)
    return Promise.resolve({
      result: 0,
      msg: '请求失败'
    })
  })
}
